import 'package:flutter/material.dart';
import '../../widgets/menu_button.dart';
import '../system/fontsize_provider.dart';
import 'package:provider/provider.dart';
import 'package:flutter/services.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
import '../../services/api_service.dart';
import '../../services/auth_service.dart';

class InventoryScreen extends StatefulWidget {
  const InventoryScreen({super.key});
  
  @override
  _InventoryScreenState createState() => _InventoryScreenState();
}

class _InventoryScreenState extends State<InventoryScreen> with WidgetsBindingObserver {
  static double _fontScale = 0.7;
  int? count = 0;
  int? moveCount = 0;
  int? warehouseId;
  
  @override
  void initState() {
    super.initState();
    _getTasks();
  }

  _getTasks() async{
    final response = await _callTaskAPI();
    setState(() {
      count = response['total_cycle'];
      moveCount = response['total_move'];
      // count = 5;
      // moveCount = 9;
    });
  }

  Future<Map<String,dynamic>> _callTaskAPI() async {

    final String param ='page=1&limit=100';
    final apiUrl = '${ApiService.baseURL}${ApiService.getMoveOrCountTasks}$param';
    
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;
    
    try {
      final response = await http.get(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type':'application/json',
          'X-Client-Type':'app'
        },
      );
      print('apiUrl---:$apiUrl');
      print('warehouseId---:$warehouseId');
      
      if (response.statusCode == 200) {
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        print('jsonData---:$jsonData');
        return jsonData;
      } else if (response.statusCode == 401) {
        AuthService auth = AuthService();
        auth.logout(context);
        throw Exception('The session has expired, Please log in again.');
      } else {
        throw Exception('Server error: ${response.statusCode}');
      }
    } catch (e) {
      throw Exception('$e');
    }
  }
  
  @override
  Widget build(BuildContext context) {
    _fontScale = Provider.of<FontSizeProvider>(context).fontScale;
    final user = Provider.of<AuthService>(context).currentUser;
    warehouseId = user?.warehouse;
    return Scaffold(
      appBar: AppBar(
        title: Text('Inventory',style: TextStyle(fontSize: 18 * _fontScale)),
        automaticallyImplyLeading: false,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back,color: Color.fromARGB(255, 255, 255, 255)),
          onPressed: () => Navigator.pushNamed(context, '/home'),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.home,color: Color.fromARGB(255, 255, 255, 255)),
            onPressed: () => Navigator.pushNamed(context, '/home'),
          ),
        ],
        backgroundColor: const Color(0xFF008363)
      ),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 32,vertical: 16),
        child: GridView.count(
          crossAxisCount: 2,
          crossAxisSpacing: 16,
          mainAxisSpacing: 16,
          childAspectRatio: 1.3,
          children: [
            MenuButton(
              icon: Icons.move_up_rounded,
              label: 'Move',
              color: Colors.green,
              // onTap: () => Navigator.pushNamed(context, '/inventory/move-stock'),
              onTap: () {
                if(moveCount != null && moveCount! > 0){
                  Navigator.of(context).pop();
                   Navigator.pushNamed(context, '/inventory/move');
                } else {
                  Navigator.pushNamed(context, '/inventory/move-stock');
                }
              },
              badgeCount: moveCount,
            ),
            MenuButton(
              icon: Icons.bookmark_remove,
              label: 'Adjustment',
              color: Colors.blue,
              onTap: () => Navigator.pushNamed(context, '/inventory/inv-adjustment-detail'),
            ),
            MenuButton(
              icon: Icons.move_to_inbox,
              label: 'Cycle Count',
              color: Colors.orange,
              onTap: () {
                if(count != null && count! > 0){
                  // 显示带关闭按钮的提示对话框
                  showDialog(
                    context: context,
                    barrierDismissible: false, // 不允许点击外部关闭
                    builder: (BuildContext context) {
                      return AlertDialog(
                        // 使用contentPadding控制内边距，为右上角按钮留出空间
                        contentPadding: const EdgeInsets.only(left: 20,right: 15,top: 10,bottom: 0),
                        // 通过Stack实现右上角关闭按钮
                        title: Stack(
                          children: [
                            Text(
                              'Warning',
                              style: TextStyle(
                                fontSize: 18 * _fontScale, 
                                color: const Color.fromARGB(255, 240, 98, 2),
                                fontWeight: FontWeight.bold
                              ),
                            ),
                            // 右上角关闭按钮
                            Positioned(
                              top: -15,
                              right: 0,
                              child: IconButton(
                                icon: Icon(
                                  Icons.close,
                                  color: Colors.grey[500],
                                  size: 20 * _fontScale,
                                ),
                                onPressed: () {
                                  // 仅关闭弹窗，不跳转
                                  Navigator.of(context).pop();
                                },
                                padding:EdgeInsets.all(0),
                                splashRadius: 20, // 减小点击反馈范围
                              ),
                            ),
                          ],
                        ),
                        content: SingleChildScrollView(
                          child: ListBody(
                            children: <Widget>[
                              Text(
                                'You have $count unfinished count tasks. Do you want to go and handle them?',
                                style: TextStyle(fontSize: 16 * _fontScale),
                              ),
                            ],
                          ),
                        ),
                        actions: <Widget>[
                          TextButton(
                            child: Text(
                              'Ignore',
                              style: TextStyle(
                                fontSize: 16 * _fontScale,
                                color: Colors.black87
                              ),
                            ),
                            onPressed: () {
                              Navigator.of(context).pop();
                              Navigator.pushNamed(context, '/inventory/cycle-count');
                            },
                          ),
                          TextButton(
                            child: Text(
                              'GO',
                              style: TextStyle(
                                fontSize: 16 * _fontScale,
                                color: const Color(0xFF008363)
                              ),
                            ),
                            onPressed: () {
                              Navigator.of(context).pop();
                              Navigator.pushNamed(context, '/inventory/count');
                            },
                          ),
                        ],
                      );
                    },
                  );
                } else {
                  Navigator.pushNamed(context, '/inventory/cycle-count');
                }
              },
              badgeCount: count,
            ),
            MenuButton(
              icon: Icons.manage_search,
              label: 'Search',
              color: const Color.fromARGB(255, 114, 239, 112),
              onTap: () => Navigator.pushNamed(context, '/inventory/search-detail'),
            ),
            MenuButton(
              icon: Icons.move_to_inbox,
              label: 'Physical Count',
              color: Colors.grey,
              onTap:() {},
            ),
          ],
        ),
      ),
    );
  }
}
